/**
 * 营销系统路由
 */

const express = require('express');
const router = express.Router();
const { requireAdmin, requireOwnerOrAdmin, verifyToken } = require('../../middleware/auth');
const {
  createCoupon,
  getAvailableCoupons,
  claimCoupon,
  getUserCoupons,
  useCoupon,
  getUserPoints,
  addPoints,
  spendPoints,
  getPointRecords,
  calculateDiscount
} = require('../utils/marketing');

// 辅助函数：通过用户名获取用户ID
const getUserIdByUsername = (username) => {
  return new Promise((resolve, reject) => {
    const db = require('../utils/db');
    const sql = 'SELECT user_id FROM user WHERE username = ?';
    db.query(sql, [username], (err, result) => {
      if (err) {
        reject(err);
      } else if (result.length > 0) {
        resolve(result[0].user_id);
      } else {
        resolve(null);
      }
    });
  });
};

// ==================== 测试路由 ====================
/**
 * 测试路由
 */
router.get('/test', (req, res) => {
  res.json({
    code: 200,
    message: '营销系统路由正常工作',
    data: { timestamp: new Date().toISOString() }
  });
});

// ==================== 优惠券相关接口 ====================

/**
 * 创建优惠券 (管理员)
 */
router.post('/coupons', requireAdmin, async (req, res) => {
  try {
    const userId = await getUserIdByUsername(req.user.username);
    const couponData = {
      ...req.body,
      created_by: userId
    };

    const result = await createCoupon(couponData);
    
    res.json({
      code: 200,
      message: '优惠券创建成功',
      data: {
        coupon_id: result.insertId,
        ...couponData
      }
    });
  } catch (error) {
    console.error('创建优惠券失败:', error);
    res.status(500).json({
      code: 500,
      message: '创建优惠券失败',
      error: error.message
    });
  }
});

/**
 * 获取可用优惠券列表
 */
router.get('/coupons/available', verifyToken, async (req, res) => {
  try {
    const userId = req.user?.username ? await getUserIdByUsername(req.user.username) : null;
    const coupons = await getAvailableCoupons(userId);
    
    res.json({
      code: 200,
      message: '获取成功',
      data: coupons
    });
  } catch (error) {
    console.error('获取优惠券列表失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取优惠券列表失败',
      error: error.message
    });
  }
});

/**
 * 用户领取优惠券
 */
router.post('/coupons/:couponId/claim', verifyToken, async (req, res) => {
  try {
    const userId = await getUserIdByUsername(req.user.username);
    const couponId = parseInt(req.params.couponId);
    
    const result = await claimCoupon(userId, couponId);
    
    res.json({
      code: 200,
      message: '优惠券领取成功',
      data: result
    });
  } catch (error) {
    console.error('领取优惠券失败:', error);
    res.status(400).json({
      code: 400,
      message: error.message || '领取优惠券失败'
    });
  }
});

/**
 * 获取用户优惠券
 */
router.get('/coupons/my', verifyToken, async (req, res) => {
  try {
    const userId = await getUserIdByUsername(req.user.username);
    const status = req.query.status;
    
    const coupons = await getUserCoupons(userId, status);
    
    res.json({
      code: 200,
      message: '获取成功',
      data: coupons
    });
  } catch (error) {
    console.error('获取用户优惠券失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取用户优惠券失败',
      error: error.message
    });
  }
});

/**
 * 验证优惠券
 */
router.post('/coupons/validate', verifyToken, async (req, res) => {
  try {
    const { coupon_code, order_amount } = req.body;
    const userId = await getUserIdByUsername(req.user.username);
    
    // 获取优惠券信息
    const coupons = await getUserCoupons(userId, 'unused');
    const coupon = coupons.find(c => c.coupon_code === coupon_code);
    
    if (!coupon) {
      return res.status(400).json({
        code: 400,
        message: '优惠券不存在或已使用'
      });
    }
    
    // 检查是否过期
    if (new Date() > new Date(coupon.expired_at)) {
      return res.status(400).json({
        code: 400,
        message: '优惠券已过期'
      });
    }
    
    // 计算优惠金额
    const discount = calculateDiscount(coupon, order_amount);
    
    if (discount === 0) {
      return res.status(400).json({
        code: 400,
        message: `订单金额需满${coupon.min_amount}元才能使用此优惠券`
      });
    }
    
    res.json({
      code: 200,
      message: '优惠券验证成功',
      data: {
        coupon,
        discount_amount: discount,
        final_amount: order_amount - discount
      }
    });
  } catch (error) {
    console.error('验证优惠券失败:', error);
    res.status(500).json({
      code: 500,
      message: '验证优惠券失败',
      error: error.message
    });
  }
});

// ==================== 积分相关接口 ====================

/**
 * 获取用户积分信息
 */
router.get('/points/my', verifyToken, async (req, res) => {
  try {
    const userId = await getUserIdByUsername(req.user.username);
    const pointsInfo = await getUserPoints(userId);
    
    res.json({
      code: 200,
      message: '获取成功',
      data: pointsInfo
    });
  } catch (error) {
    console.error('获取用户积分失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取用户积分失败',
      error: error.message
    });
  }
});

/**
 * 获取积分记录
 */
router.get('/points/records', verifyToken, async (req, res) => {
  try {
    const userId = await getUserIdByUsername(req.user.username);
    const limit = parseInt(req.query.limit) || 20;
    const offset = parseInt(req.query.offset) || 0;
    
    const records = await getPointRecords(userId, limit, offset);
    
    res.json({
      code: 200,
      message: '获取成功',
      data: records
    });
  } catch (error) {
    console.error('获取积分记录失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取积分记录失败',
      error: error.message
    });
  }
});

/**
 * 管理员添加积分
 */
router.post('/points/add', requireAdmin, async (req, res) => {
  try {
    const { user_id, points, description } = req.body;
    
    if (!user_id || !points || points <= 0) {
      return res.status(400).json({
        code: 400,
        message: '参数错误'
      });
    }
    
    const result = await addPoints(user_id, points, 'admin', null, description || '管理员添加');
    
    res.json({
      code: 200,
      message: '积分添加成功',
      data: result
    });
  } catch (error) {
    console.error('添加积分失败:', error);
    res.status(500).json({
      code: 500,
      message: '添加积分失败',
      error: error.message
    });
  }
});

/**
 * 积分兑换
 */
router.post('/points/exchange', verifyToken, async (req, res) => {
  try {
    const userId = await getUserIdByUsername(req.user.username);
    const { points, exchange_type, description } = req.body;
    
    if (!points || points <= 0) {
      return res.status(400).json({
        code: 400,
        message: '兑换积分必须大于0'
      });
    }
    
    // 这里可以添加不同的兑换逻辑
    // 例如：积分兑换优惠券、积分抵现等
    
    const result = await spendPoints(userId, points, 'exchange', null, description || '积分兑换');
    
    res.json({
      code: 200,
      message: '积分兑换成功',
      data: result
    });
  } catch (error) {
    console.error('积分兑换失败:', error);
    res.status(400).json({
      code: 400,
      message: error.message || '积分兑换失败'
    });
  }
});

// ==================== 签到相关接口 ====================

/**
 * 用户签到
 */
router.post('/checkin', verifyToken, async (req, res) => {
  try {
    const userId = await getUserIdByUsername(req.user.username);
    const today = new Date().toISOString().split('T')[0];
    
    // 检查今天是否已签到
    const db = require('../utils/db');
    const checkSql = `SELECT * FROM user_checkins WHERE user_id = ? AND checkin_date = ?`;
    
    db.query(checkSql, [userId, today], async (err, result) => {
      if (err) {
        return res.status(500).json({
          code: 500,
          message: '签到失败',
          error: err.message
        });
      }
      
      if (result.length > 0) {
        return res.status(400).json({
          code: 400,
          message: '今天已经签到过了'
        });
      }
      
      // 获取连续签到天数
      const consecutiveSql = `
        SELECT consecutive_days FROM user_checkins 
        WHERE user_id = ? 
        ORDER BY checkin_date DESC 
        LIMIT 1
      `;
      
      db.query(consecutiveSql, [userId], async (err, consecutiveResult) => {
        if (err) {
          return res.status(500).json({
            code: 500,
            message: '签到失败',
            error: err.message
          });
        }
        
        let consecutiveDays = 1;
        if (consecutiveResult.length > 0) {
          const lastCheckin = consecutiveResult[0];
          const yesterday = new Date();
          yesterday.setDate(yesterday.getDate() - 1);
          const yesterdayStr = yesterday.toISOString().split('T')[0];
          
          // 如果昨天有签到，连续天数+1
          if (lastCheckin.checkin_date === yesterdayStr) {
            consecutiveDays = lastCheckin.consecutive_days + 1;
          }
        }
        
        // 计算签到积分（连续签到有奖励）
        let pointsEarned = 10; // 基础签到积分
        if (consecutiveDays >= 7) {
          pointsEarned = 50; // 连续7天奖励
        } else if (consecutiveDays >= 3) {
          pointsEarned = 20; // 连续3天奖励
        }
        
        // 插入签到记录
        const insertSql = `
          INSERT INTO user_checkins (user_id, checkin_date, points_earned, consecutive_days)
          VALUES (?, ?, ?, ?)
        `;
        
        db.query(insertSql, [userId, today, pointsEarned, consecutiveDays], async (err, insertResult) => {
          if (err) {
            return res.status(500).json({
              code: 500,
              message: '签到失败',
              error: err.message
            });
          }
          
          // 添加积分
          try {
            await addPoints(userId, pointsEarned, 'signin', insertResult.insertId, `签到获得积分，连续${consecutiveDays}天`);
            
            res.json({
              code: 200,
              message: '签到成功',
              data: {
                points_earned: pointsEarned,
                consecutive_days: consecutiveDays,
                checkin_date: today
              }
            });
          } catch (pointsError) {
            console.error('添加签到积分失败:', pointsError);
            res.status(500).json({
              code: 500,
              message: '签到成功但积分添加失败'
            });
          }
        });
      });
    });
  } catch (error) {
    console.error('签到失败:', error);
    res.status(500).json({
      code: 500,
      message: '签到失败',
      error: error.message
    });
  }
});

/**
 * 获取签到状态
 */
router.get('/checkin/status', verifyToken, async (req, res) => {
  try {
    const userId = await getUserIdByUsername(req.user.username);
    const today = new Date().toISOString().split('T')[0];
    
    const db = require('../utils/db');
    const sql = `
      SELECT 
        CASE WHEN c1.checkin_date IS NOT NULL THEN 1 ELSE 0 END as checked_today,
        COALESCE(c2.consecutive_days, 0) as consecutive_days
      FROM (SELECT 1) dummy
      LEFT JOIN user_checkins c1 ON c1.user_id = ? AND c1.checkin_date = ?
      LEFT JOIN (
        SELECT consecutive_days FROM user_checkins 
        WHERE user_id = ? 
        ORDER BY checkin_date DESC 
        LIMIT 1
      ) c2 ON 1=1
    `;
    
    db.query(sql, [userId, today, userId], (err, result) => {
      if (err) {
        return res.status(500).json({
          code: 500,
          message: '获取签到状态失败',
          error: err.message
        });
      }
      
      res.json({
        code: 200,
        message: '获取成功',
        data: result[0] || { checked_today: 0, consecutive_days: 0 }
      });
    });
  } catch (error) {
    console.error('获取签到状态失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取签到状态失败',
      error: error.message
    });
  }
});

module.exports = router;
